package com.cloud.jucTest;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;

/**
 * fork : 任务拆分
 * join : 任务合并
 */
public class ForkTestDemo {
    private static final Integer MAX = 50;

    static class SubTask extends RecursiveTask<Integer> {

        private Integer start;

        private Integer end;

        public SubTask (Integer start, Integer end) {
            this.start = start;
            this.end = end;
        }

        @Override
        protected Integer compute() {
            if (end - start < MAX) {
                System.out.println("start = " + start + ";end = " + end);
                Integer totalValue = 0;
                for (int index = this.start; index <= this.end; ++index) {
                    totalValue += index;
                }
                return totalValue;
            } else {
                SubTask subTask1 = new SubTask(start, (start + end) / 2);
                subTask1.fork();
                SubTask subTask2 = new SubTask((start + end) / 2 + 1, end);
                subTask2.fork();
                return subTask1.join() + subTask2.join();
            }
        }

        public static void main(String[] args) {
            ForkJoinPool pool = new ForkJoinPool();
            Future<Integer> taskFuture = pool.submit(new SubTask(1, 1000));

            try {
                Integer result = taskFuture.get();
                System.out.println("the finally result is " + result);
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace(System.out);
            }

        }
    }
}
